<template>
  <div class="app-container">
    <el-card shadow="never" class="mb-10">
      <el-descriptions class="mb-20" direction="vertical" border>
        <template #title>
          <div class="flex items-center">
            <div class="w-10 h-10 bg-accent-color" />
            <div class="font-bold text-333333 text-16 ml-10">应用信息</div>
          </div>
        </template>
        <el-descriptions-item label="应用名称">{{ userInfo.appName }}</el-descriptions-item>
        <el-descriptions-item label="client_id">
          <span>{{ userInfo.clientId }}</span>
          <el-button class="ml-10" type="primary" link @click="copyText(userInfo.clientId)">
            复制
          </el-button>
        </el-descriptions-item>
        <el-descriptions-item label="client_secret">
          {{ userInfo.auditStatus == 1 ? userInfo.clientSecret : "授权店铺后才可以获取" }}
          <template v-if="userInfo.auditStatus == 1">
            <el-button class="ml-10" type="primary" link @click="openClientDialog(1)">
              查看
            </el-button>
            <el-button
              v-if="hasOperatePermission"
              class="ml-10"
              type="primary"
              link
              @click="openClientDialog(2)"
            >
              重置
            </el-button>
          </template>
        </el-descriptions-item>
      </el-descriptions>
      <el-descriptions class="mb-20" direction="vertical" border>
        <template #title>
          <div class="flex items-center">
            <div class="w-10 h-10 bg-accent-color" />
            <div class="font-bold text-333333 text-16 ml-10">店铺授权信息</div>
          </div>
        </template>
        <el-descriptions-item label="店铺名称">
          {{ userInfo.companyName }}
          <span v-if="expire" class="ml-10">(店铺已过期)</span>
          <span v-if="userInfo.auditOtherCompany == 1" class="ml-10">(店铺已授权其他应用)</span>
        </el-descriptions-item>
        <el-descriptions-item label="店铺id">
          <span>{{ userInfo.companyId }}</span>
          <el-button class="ml-10" type="primary" link @click="copyText(userInfo.companyId)">
            复制
          </el-button>
        </el-descriptions-item>
        <el-descriptions-item label="授权状态">
          {{ auditStatusMap[userInfo.auditStatus] || "--" }}
          <el-button
            v-if="(userInfo.auditStatus == -1 || userInfo.auditStatus == 0) && hasOperatePermission"
            class="ml-10"
            type="primary"
            link
            @click="applyAppAuth(userInfo.status, userInfo.auditStatus)"
          >
            {{ statusMap[userInfo.auditStatus] || "--" }}
          </el-button>
        </el-descriptions-item>
      </el-descriptions>
      <el-descriptions class="mb-20" direction="vertical" border>
        <template #title>
          <div class="flex items-center">
            <div class="w-10 h-10 bg-accent-color" />
            <div class="font-bold text-333333 text-16 ml-10">IP白名单</div>
            <div class="text-red-600 text-14">(必填)</div>
            <div class="text-14">（仅添加的白名单才能访问创客匠人的API）</div>
          </div>
          <el-button
            v-if="hasOperatePermission"
            class="mt-10"
            type="primary"
            @click="openClientDialog(3)"
          >
            去配置
          </el-button>
        </template>
        <el-descriptions-item label="配置IP" class-name="flex gap-10">
          <div class="flex flex-wrap gap-10">
            <template v-if="userInfo.ipWhiteList && userInfo.ipWhiteList.length > 0">
              <el-tag
                v-for="item in userInfo.ipWhiteList"
                :key="item"
                :closable="hasOperatePermission"
                type="primary"
                @close="delIp(item)"
              >
                {{ item }}
              </el-tag>
            </template>
            <template v-else>暂未设置IP</template>
          </div>
        </el-descriptions-item>
      </el-descriptions>
      <el-descriptions class="mb-20" direction="vertical" border>
        <template #title>
          <div class="flex items-center">
            <div class="w-10 h-10 bg-accent-color" />
            <div class="font-bold text-333333 text-16 ml-10">消息接收</div>
          </div>
          <el-button
            v-if="hasOperatePermission"
            class="mt-10"
            type="primary"
            @click="openClientDialog(4)"
          >
            设置
          </el-button>
        </template>
        <el-descriptions-item label="消息签名">
          {{ userInfo.msgSign || "--" }}
        </el-descriptions-item>
        <el-descriptions-item label="消息接收URL">
          {{ userInfo.msgUrl || "--" }}
          <div class="text-999999">
            填写URL后，创客匠人服务器将向其发送模拟消息请求用于校验地址有效性，服务端接收请求后，请2秒内返回success
          </div>
        </el-descriptions-item>
      </el-descriptions>
    </el-card>
    <DashboardDialog
      v-if="dashboardDialogVisible"
      :model-value="dashboardDialogVisible"
      :details-type="dashboardDialogType"
      @cancel="dashboardDialogVisible = false"
      @confirm="confirmDashboardDialog"
      @resetUserInfo="resetUserInfo"
    />
  </div>
</template>

<script setup lang="ts">
import { useUserStore } from "@/store";
import { UserInfo } from "@/api/system/user";
import { copyText } from "@/utils";
import DashboardDialog from "@/views/dashboard/components/DashboardDialog.vue";
import DashboardAPI from "@/api/dashboard";
import { getHasOperatePermission } from "@/utils/auth";
// 判断是否拥有权限
const hasOperatePermission: boolean = getHasOperatePermission();
// 用户状态管理器
const userStore = useUserStore();
// 获取用户信息
let userInfo: UserInfo = userStore.userInfo;
// 店铺是否到期
const expire = ref<boolean>(false);
// 详情弹出框是否展示
const dashboardDialogVisible = ref<boolean>(false);
// 详情弹出框类型
const dashboardDialogType = ref<number>(1);
// 授权状态
const auditStatusMap: Record<string, string> = {
  [-1]: "已拒绝",
  0: "未授权",
  1: "已授权",
  2: "待授权",
};
// 审核状态
const statusMap: Record<string, string> = {
  [-1]: "重新发起授权",
  0: "发起授权",
  1: "",
  2: "",
};
// 防止多次点击
const btnLoading = ref<boolean>(false);

// 查看弹出框
const openClientDialog = (dialogType: number) => {
  dashboardDialogType.value = dialogType;
  dashboardDialogVisible.value = true;
};
// 删除ID
const delIp = (ip: string) => {
  ElMessageBox.confirm("确定删除该IP地址？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      DashboardAPI.removeIpAddress({ ip })
        .then(async (res) => {
          btnLoading.value = false;
          getUserInfo("删除ip成功!");
        })
        .catch(() => {
          btnLoading.value = false;
        });
    })
    .catch(() => {
      ElMessage.info("取消删除");
    });
};
// 获取用户信息
const getUserInfo = (tips: string) => {
  userStore.getUserInfo().then((data) => {
    userInfo = data;
    ElMessage.success(tips);
  });
};
// 申请授权
const applyAppAuth = (status: number, auditStatus: number) => {
  if ((status == 1 && auditStatus == 0) || (status == 1 && auditStatus == -1)) {
    DashboardAPI.applyAppAudit()
      .then(async (res) => {
        btnLoading.value = false;
        getUserInfo("申请授权成功!");
      })
      .catch(() => {
        btnLoading.value = false;
      });
  } else {
    ElMessage.success("申请授权失败!");
  }
};
// 重置用户信息
const resetUserInfo = (userParam: UserInfo) => {
  userInfo = userParam;
  const TimeStamp =
    new Date(userInfo.expireTime).getTime() - new Date(userInfo.createdAt).getTime();
  const nowTimeStamp = new Date().getTime() - new Date(userInfo.createdAt).getTime();
  if (nowTimeStamp - TimeStamp >= 0) {
    expire.value = true;
  }
};
// 保存详情弹出框
const confirmDashboardDialog = () => {
  dashboardDialogVisible.value = false;
};
</script>

<style scoped lang="scss"></style>
